package com.dhc.appbusinessfrm.presenter;

import android.text.TextUtils;

import com.dhc.appbusinessfrm.R;
import com.dhc.appbusinessfrm.business.common.NetworkBusiness;
import com.dhc.appbusinessfrm.business.login.LoginBusiness;
import com.dhc.appbusinessfrm.business.login.LoginCallback;
import com.dhc.appbusinessfrm.model.MsgParseEnum;
import com.dhc.appbusinessfrm.model.ResultModel;
import com.dhc.appbusinessfrm.util.MD5;
import com.dhc.appbusinessfrm.view.activity.LoginInteractor;

import java.util.concurrent.Future;

import javax.inject.Inject;

/**
 * Created by xy on 2015/6/11.
 */
public class LoginPresenterImpl extends BasePresenterImpl implements LoginPresenter {

    private LoginInteractor loginInteractor;

    public LoginPresenterImpl(LoginInteractor loginInteractor) {
        super(loginInteractor);
        this.loginInteractor = loginInteractor;
    }

    /**
     * 注入网络业务类
     */
    @Inject
    NetworkBusiness networkBusiness;

    /**
     * 注入登录业务类
     */
    @Inject
    LoginBusiness loginBusiness;

    @Override
    public void ini() {
        // 获取本地存储的用户名
        String loginName = preferenceUtils.getLoginName();
        // 显示在用户名输入框中
        loginInteractor.setEdtLoginName(loginName);
    }

    /**
     * 登录检查
     */
    @Override
    public boolean checkLogin() {
        // 获取用户名
        String loginName = loginInteractor.getLoginName();
        // 获取密码
        String password = loginInteractor.getPassword();
        // 用户名输入判断
        if (TextUtils.isEmpty(loginName)) {
            // 未输入用户名，弹出Toast提醒用户，返回
            loginInteractor.showShortPrompt(R.string.input_login_name_label);
            return false;
        }
        // 密码输入判断
        if (TextUtils.isEmpty(password)) {
            // 未输入密码，弹出Toast提醒用户，返回
            loginInteractor.showShortPrompt(R.string.input_password_label);
            return false;
        }
        return true;
    }

    /**
     * 登录
     */
    @Override
    public void doLogin() {
        if (!checkLogin())
            return;
        // 获取用户名
        String loginName = loginInteractor.getLoginName();
        // 获取密码
        String password = loginInteractor.getPassword();
        // 登录
        Future future = loginBusiness.login(loginName, MD5.getMD5Str(password), loginCallback);
    }

    /**
     * 登录业务回调函数
     */
    LoginCallback loginCallback = new LoginCallback() {

        @Override
        public void netSuccess(ResultModel resultModel) {
            //TODO 跳转至首页

            // 关闭本窗体
            loginInteractor.finishActivity();
        }

        @Override
        public void netFailure(int errorId) {
            int stringId = MsgParseEnum.getValue(errorId);
            loginInteractor.showLongPrompt(stringId);
        }
    };
}
